<template>
  <brand-background>
    <template #page>
      <div class="login">
        <div class="form-wrapper">
          <div class="tab-box">
            <div :class="['tab--active', 'tab']">账号注册</div>
          </div>
          <a-form ref="formRef" class="login-form" :model="formState" name="form" :rules="rules">
            <a-form-item name="tel">
              <g-input v-model:value="formState.tel" size="large" :maxlength="11" placeholder="请输入手机号" class="w-360" />
            </a-form-item>
            <a-form-item name="password">
              <a-input-password
                v-model:value="formState.password"
                size="large"
                autocomplete="off"
                placeholder="请输入新密码"
                :maxlength="15"
                @input="formState.password = formState.password.replace(/\s+/g, '')"
              />
            </a-form-item>
            <a-form-item name="confirmPassWord">
              <a-input-password
                v-model:value="formState.confirmPassWord"
                size="large"
                autocomplete="off"
                placeholder="请输入确认密码"
                :maxlength="15"
                @input="formState.confirmPassWord = formState.confirmPassWord.replace(/\s+/g, '')"
              />
            </a-form-item>
            <a-form-item name="invitationCode">
              <g-input v-model:value="formState.invitationCode" size="large" placeholder="请输入邀请码" class="w-360" />
            </a-form-item>
          </a-form>

          <a-button size="large" block class="btn-submit" type="primary" @click="submit"> 注册并登录</a-button>
          <div class="fc mt-8">
            <a-button type="link" @click="() => router.push('/')">已有账号？去登录</a-button>
          </div>
        </div>
      </div>
    </template>
  </brand-background>
</template>

<script lang="ts" setup>
  import { Rule } from 'ant-design-vue/es/form'
  import { cloneDeep, regex, useSM4 } from 'g6-fn'
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute, useRouter } from 'vue-router'

  import { SM4_KEY } from '@/config'
  import { loginApi } from '@/services'
  import { useUserInfoStore } from '@/store'

  import BrandBackground from '../components/BrandBackground.vue'

  const router = useRouter()
  const { encrypt } = useSM4(SM4_KEY)
  const userInfoStore = useUserInfoStore()
  const formState = ref({
    tel: '',
    password: '',
    confirmPassWord: '',
    invitationCode: ''
  })
  const formRef = ref()

  //密码校验规则
  const passwordVerifyRule = (value: string) => {
    // 检查密码长度
    if (!value) {
      return Promise.reject('请输入密码')
    } else if (value.length < 8 || value.length > 15) {
      return Promise.reject('密码的长度为8-15位')
    }

    // 定义正则表达式，要求包含大、小写字母、数字和特殊字符中的三项
    const regex =
      /^(?:(?=.*[a-z])(?=.*[A-Z])(?=.*\d)|(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])|(?=.*[a-z])(?=.*\d)(?=.*[\W_])|(?=.*[A-Z])(?=.*\d)(?=.*[\W_]))[^\u4e00-\u9fa5\u3040-\u30FF\uAC00-\uD7AF]+$/

    if (!regex.test(value)) {
      return Promise.reject('密码至少包含大、小写字母、数字和特殊字符中的三项')
    }

    return Promise.resolve()
  }

  //校验密码
  let validatePWS = async (rule: Rule, value: string) => {
    if (value === '') {
      return Promise.reject('请输入新密码')
    }
    return passwordVerifyRule(value)
  }
  //确认密码
  let validateAckPWS = async (rule: Rule, value: string) => {
    if (value === '') {
      return Promise.reject('请输入确认密码')
    }
    if (value !== formState.value.password) {
      return Promise.reject('两次输入的新密码不一致')
    }
    return Promise.resolve()
  }
  const rules: Record<string, Rule[]> = {
    tel: [{ required: true, pattern: regex.phone, trigger: 'change', message: '请输入正确的手机号' }],
    password: [{ required: true, validator: validatePWS, trigger: 'change' }],
    confirmPassWord: [{ required: true, validator: validateAckPWS, trigger: 'change' }],
    invitationCode: [{ required: true, trigger: 'change', message: '请输入邀请码' }]
  }

  const { loading: updatePwsLoading, runAsync: runRegister } = useRequest<ResponseData<any>>(loginApi.register)
  const submit = async () => {
    await formRef.value?.validateFields()
    const params = cloneDeep(formState.value)
    params.password = encrypt(params.password)
    params.confirmPassWord = encrypt(params.confirmPassWord)
    const res = await runRegister(params)
    loginAfter(res.data.token)
  }

  /* 登陆之后的统一操作 */
  const loginAfter = async (token: string) => {
    userInfoStore.changeToken(token)
    await userInfoStore.getUserInfo()
    await userInfoStore.getMenuData()

    router.replace('/')
  }
</script>

<style lang="less" scoped>
  @import '../styles/index.less';

  .login {
    display: flex;
    justify-content: center;
    // height: 100vh;
    height: 100%;
    background-color: @background1;
    flex-direction: column;

    .form-wrapper {
      margin: 0 auto;
      width: 360px;
      height: 480px;

      .tab-box {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        color: @text04;
        .font20b();

        .tab {
          position: relative;
          width: 50%;
          text-align: center;
          cursor: pointer;

          &--active {
            position: relative;
            margin-top: 1px;
            color: @text01;
          }
        }
      }

      .login-form {
        padding: 36px 0 0;

        .ant-form-item {
          margin-bottom: 24px;

          &:nth-child(4) {
            margin-bottom: 0;
            .auth-code-wrapper();
          }
        }
      }

      .forgot-password {
        display: inline-block;
        margin-top: 8px;
        color: @link;
        cursor: pointer;
      }

      .btn-submit {
        margin-top: 32px;
        color: rgba(255, 255, 255, 1);
        background: #1868e9;
      }
    }
  }
</style>
